package com.polytech.diploma.OracleStat.Parsers;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.polytech.diploma.OracleStat.SQLStatData;

public class FingerPrintsParser {
	
	protected static String ConstFieldPattern = "\'[^\']{1,}\'";
	protected static String ConstFieldFingerprint = "@LITERAL";
	
	protected static String NumberFieldPattern = "(\\W{1,})(\\d{1,})";
	protected static String NunberFieldFingerprint = "@NUMBER";
	
	public static SQLStatData doParse(SQLStatData data)	
	{
		String sqlQuery = data.getSqlText();
		sqlQuery = sqlQuery.replace("''", "");
		
		Pattern constFieldPattern = Pattern.compile(ConstFieldPattern, Pattern.CASE_INSENSITIVE);
		Matcher constFieldMatcher = constFieldPattern.matcher(sqlQuery);
		int i=1;
		StringBuffer buffer = new StringBuffer();
		
		while(constFieldMatcher.find())
		{
			data.addToReplaceList(ConstFieldFingerprint + i, constFieldMatcher.group());
			constFieldMatcher.appendReplacement(buffer, ConstFieldFingerprint + i++);			
		}
		constFieldMatcher.appendTail(buffer);
		sqlQuery = buffer.toString();
		//sqlQuery = constFieldMatcher.replaceAll(ConstFieldFingerprint);
		
		
		Pattern numberFieldPattern = Pattern.compile(NumberFieldPattern, Pattern.CASE_INSENSITIVE);
		Matcher numberFieldMatcher = numberFieldPattern.matcher(sqlQuery);
		buffer = new StringBuffer();
		i=1;
		
		while(numberFieldMatcher.find())
		{
			data.addToReplaceList(numberFieldMatcher.group(1)+ NunberFieldFingerprint + i, numberFieldMatcher.group(2));
			numberFieldMatcher.appendReplacement(buffer, NunberFieldFingerprint + i++);	
		}
		numberFieldMatcher.appendTail(buffer);
		//sqlQuery = numberFieldMatcher.replaceAll(NunberFieldFingerprint);
		data.setSqlText(buffer.toString());
		return data;
	}
}
